<template>
  <div >
    <el-page-header @back="goBack" content="资讯编辑"> </el-page-header>
    <div class="div1" style="margin:20px 0;">
      <el-input v-model="titleinput" placeholder="请输入文章标题（5~30个字）" class="titleinput" size="medium" minlength="5" maxlength="30" show-word-limit>
        <el-button slot="append" type="primary" round  size="small" @click="publish">发布资讯</el-button>

      </el-input>
    </div>
    <div class="div2" style="height:400px;min-height:400px;">
      <mavon-editor
          v-model="editorContent"
          :ishljs="true"
          :autofocus="false"
          ref=md
      ></mavon-editor>

      <el-upload
          action="#"
          list-type="picture-card"
          multiple
          name="imgFile"
          :limit="1"
          ref="uploadImg"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemovePicture"
          :on-exceed="handleExceedPicture"
          :http-request="uploadImg"
          :on-change="handleChangePicture"
          :auto-upload="false"
          accept=".png, .jpg"
          :file-list="imgList"
      >
        <i class="el-icon-plus"></i>

        <div class="el-upload__tip" style="margin-top: 0;" slot="tip">添加封面图片，只能上传.jpg/.png图片，且不超过10Mb</div>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
    </div>

  </div>
</template>

<script>
import { mavonEditor } from 'mavon-editor'
import 'mavon-editor/dist/css/index.css';
import axios from "axios";
//vue默认header
const token = localStorage.getItem("admin_TOKEN");
axios.defaults.headers.common['TOKEN'] = token;
export default {
  name:'MarkDown',
  data(){
    return {
      titleinput: "",
      editorContent: "",
      fileData:'',
      imgList: [],
      dialogImageUrl: '',
      newsId:'',
      coverUrl:'',
      dialogVisible:false,
    }
  },

  components: {
    mavonEditor
  },

  created(){
    let news = this.$route.params.key;
    if(news!=null){
      this.newsId = news.newsId;
      this.editorContent= news.newsContent;
      this.titleinput=news.newsTitle;
      this.coverUrl = news.coverUrl;
    }

  },

  mounted(){
    window.addEventListener("beforeunload", this.beforeUnloadHandler, false)

  },
  destroyed() {
    window.removeEventListener("beforeunload", this.beforeUnloadHandler, false)
  },

  methods: {
    uploadImg(file) {
      this.fileData.append('img', file.file);  // append增加数据
    },
    publish(){
      if(this.titleinput==null||this.titleinput==''){
        this.$message.warning("标题不能为空");
        return;
      }
      if(this.editorContent==null||this.editorContent==''){
        this.$message.warning("内容不能为空");
        return;
      }
      const isLt10M = this.imgList.every(file => file.size / 1024/1024  < 10);
      if (!isLt10M) {
        this.$message.error('请检查，上传图片大小不能超过10MB!');
        return;
      }
      if(this.newsId==null||this.newsId==''){
        this.fileData = new FormData();  // new formData对象
        this.$refs.uploadImg.submit();
        this.fileData.append('newsTitle', this.titleinput);  // 添加机构id
        this.fileData.append('newsContent', this.editorContent);  // 添加token
        axios.post("/api/news/addNews/upload/?ser=community",this.fileData,).then(response => {
          if (response.data.code === 100) {
            this.$message.success(response.data.data);
            this.imgList=[];
            this.goBack();
          }else{
            this.$message.error(response.data.msg);
          }
        })
      }else{
        this.fileData = new FormData();  // new formData对象
        this.$refs.uploadImg.submit();
        this.fileData.append('newsTitle', this.titleinput);  //
        this.fileData.append('newsContent', this.editorContent);  //
        this.fileData.append('newsId', this.newsId);  //
        axios.post("/api/news/updateNews/upload/?ser=community",this.fileData,).then(res =>{
          if(res!=null){
            this.$message.info(res.data.data);
            this.imgList=[];
            this.goBack();
          }}
        )

      }
    },
    goBack(){
        this.$router.push({name:'newsManage'})
    },
    // 此处返回任意字符串，不返回null即可，不能修改默认提示内容
    beforeUnloadHandler(e) {
      e.returnValue = "离开此页面？"
    },
    handleRemovePicture(file, fileList) {
      this.imgList = fileList;
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleExceedPicture(){
      this.$message.warning("文件已存在，请先移除")
    },
    handleChangePicture(file, fileList) {
      let existFile = fileList.slice(0, fileList.length - 1).find(f => f.name === file.name);
      if (existFile) {
        this.$message.error('当前文件已经存在!');
        fileList.pop();
      }
      this.imgList = fileList;
    },
  }
}
</script>

<style scoped>


</style>
